package server.core;

import org.apache.catalina.*;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SimplePipeline implements Pipeline, Lifecycle {
    public SimplePipeline(Container container) {
        setContainer(container);
    }
    private Valve basic = null;
    private List<Valve> valves = new ArrayList<>();
    private Container container = null;
    public void setContainer(Container container) {
        this.container = container;
    }
    //实现Pipeline接口--------------------------------------------------------------
    @Override
    public Valve getBasic() {
        return basic;
    }

    @Override
    public void setBasic(Valve valve) {
        this.basic = valve;
        ((Contained)valve).setContainer(container);
    }

    @Override
    public void addValve(Valve valve) {
        if (valve instanceof Contained)
            ((Contained) valve).setContainer(this.container);
        synchronized (valves) {
            valves.add(valve);
        }
    }

    @Override
    public Valve[] getValves() {
        return (Valve[])valves.toArray();
    }

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        for (Valve valve : valves) {
            valve.invoke(request, response, null);
        }
        if (basic != null) {
            basic.invoke(request, response, null);
        } else {
            throw new ServletException("No valve");
        }
    }

    @Override
    public void removeValve(Valve valve) {

    }

    //实现Lifecycle接口--------------------------------------------------------------
    @Override
    public void addLifecycleListener(LifecycleListener listener) {

    }

    @Override
    public LifecycleListener[] findLifecycleListeners() {
        return new LifecycleListener[0];
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {

    }

    @Override
    public void start() throws LifecycleException {

    }

    @Override
    public void stop() throws LifecycleException {

    }
}
